package com.ailink.design.pattern.singleton;

/**
 * Created by Administrator on 2018/9/19
 * 1 memory = allocate() 分配对象的内存空间
 * 2 ctorInstance() 初始化对象
 * 3 instance = memory 设置instance指向刚分配的内存
 *
 * JVM和cpu优化，发生了指令重排
 *
 * 1 memory = allocate() 分配对象的内存空间、
 * 3 instance = memory 设置instance指向刚分配的内存
 * 2 ctorInstance() 初始化对象
 *
 * 线程1执行到B位置的指令重排后的3位置的时候
 * 线程1暂停
 * 线程2执行到A位置，判断instance是否为空，此时不为空，线程2就拿到了一个未被初始化的instance
 */
public class LazyDoubleCheckSingleton {

    private volatile static LazyDoubleCheckSingleton lazyDoubleCheckSingleton = null;

    private LazyDoubleCheckSingleton() {}

    public static LazyDoubleCheckSingleton getInstance() {
        if (lazyDoubleCheckSingleton == null) { // A位置
            synchronized (LazyDoubleCheckSingleton.class) {
                if (lazyDoubleCheckSingleton == null) {
                    lazyDoubleCheckSingleton = new LazyDoubleCheckSingleton(); //B位置
                }
            }
        }
        return lazyDoubleCheckSingleton;
    }
}
